import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/routes/goods/model/EcyGoodsHomeIPListModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyLogger.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../model/EcyGoodsHomeIPModel.dart';

//ip列表
class EcyGoodsHomeIPListView extends StatefulWidget {
  late _EcyGoodsHomeIPListViewState currentState;
  final ValueChanged<EcyGoodsHomeIPModel> onSelectNewValue;
  @override
  State<StatefulWidget> createState() {
    currentState = _EcyGoodsHomeIPListViewState(onSelectNewValue);
    return currentState;
  }

  EcyGoodsHomeIPListView(this.onSelectNewValue);

  reloadData(EcyGoodsHomeIPListModel ipListModel) {
    currentState.reloadData(ipListModel);
  }

  refreshData() {
    currentState._refreshData(page: 1);
  }
}

class _EcyGoodsHomeIPListViewState extends State {
  final ScrollController _scrollController = ScrollController();
  String selectdIPId = "";
  List<EcyGoodsHomeIPModel> _ipList = [];
  int _total = 0;
  int _page = 1;
  final ValueChanged<EcyGoodsHomeIPModel> onSelectNewValue;
  final allIp = EcyGoodsHomeIPModel("全部", "-1", "全部", "-1",
      "assets/images/ic_home_ip_all_blue.png", false, false, "-1");
  final _settingIp = EcyGoodsHomeIPModel("设置自选", "-2", "设置自选", "-2",
      "assets/images/ic_home_ip_all_setting.png", false, false, "-2");

  _EcyGoodsHomeIPListViewState(this.onSelectNewValue);

  reloadData(EcyGoodsHomeIPListModel ipListModel) {
    _total = ipListModel.pages;
    _page = ipListModel.current;
    List<EcyGoodsHomeIPModel> ipList = [allIp];
    if (ipListModel.records.isNotEmpty) {
      ipList.addAll(ipListModel.records);
    }
    if(mounted) {
      setState(() {
        _ipList = ipList;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
  }

  void _onScroll() {
    if (_page < _total) {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _refreshData(page: ++_page); // 加载更多数据的函数
      }
    }
  }

  Future<bool> _refreshData({int page = 2}) async {
    if (page == 1) {
      _ipList.clear();
      _ipList.add(allIp);
    }
    try {
      Map<String, dynamic> response = await EcyRequestbasemanager().post(
          "/app/api/app/commodityIp/list", {"size": "50", "current": page});
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        EcyGoodsHomeIPListModel ipListModel =
            EcyGoodsHomeIPListModel.fromJson(response["data"]);
        _total = ipListModel.pages;
        _page = ipListModel.current;
        if (ipListModel.records.isNotEmpty) {
          setState(() {
            _ipList.addAll(ipListModel.records);
          });
        }
      }
    } catch (e) {
      EcyLogger.log("获取IP失败");
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    var _this = this;
    return Row(
      children: _ipList.isEmpty
          ? []
          : [
              Expanded(
                flex: 4,
                child: ListView.builder(
                    shrinkWrap: true,
                    physics: const AlwaysScrollableScrollPhysics(),
                    scrollDirection: Axis.horizontal, // 设置滚动方向为水平
                    itemCount: _ipList.isNotEmpty ? _ipList.length - 1 : 0,
                    controller: _scrollController,
                    itemBuilder: (context, index) {
                      var item = _ipList[index];
                      return Container(
                          width: MediaQuery.of(context).size.width / 5,
                          alignment: Alignment.center,
                          padding: EdgeInsets.only(top: 8.h),
                          child: GestureDetector(
                              onTap: () {
                                if (_this.onSelectNewValue != null) {
                                  _this.onSelectNewValue(item);
                                }
                                _this.setState(() {
                                  if (item.id == "-1") {
                                    selectdIPId = "";
                                  } else if (item.id == "-2") {
                                  } else {
                                    selectdIPId = item.id ?? "";
                                  }
                                });
                              },
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  renderItem(item),
                                  SizedBox(height: 2.w),
                                  Expanded(
                                    child: RichText(
                                      overflow: TextOverflow.ellipsis,
                                      textAlign:
                                          TextAlign.center, // 设置文本对齐方式为居中
                                      text: TextSpan(
                                        style: TextStyle(
                                            fontWeight: selectdIPId == item.id
                                                ? FontWeight.w600
                                                : FontWeight.w300,
                                            fontSize: 12.sp,
                                            color: selectdIPId == item.id
                                                ? const Color(0xFFEA4B9B)
                                                : const Color(
                                                    0xD9000000)), // 使用默认文本样式
                                        children: [
                                          TextSpan(
                                            text: item.name ?? "",
                                          ), // 换行符用于换行
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              )));
                    }),
              ),
              Expanded(
                flex: 1,
                child: Container(
                    width: MediaQuery.of(context).size.width / 5,
                    alignment: Alignment.center,
                    padding: EdgeInsets.only(top: 8.h),
                    margin: EdgeInsets.only(left: 0.h),
                    child: GestureDetector(
                        onTap: () {
                          if (_this.onSelectNewValue != null) {
                            _this.onSelectNewValue(_settingIp);
                          }
                        },
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            renderItem(_settingIp),
                            SizedBox(height: 5.h),
                            Text(
                              _settingIp.name ?? "",
                              style: TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: selectdIPId == _settingIp.id
                                      ? FontWeight.w600
                                      : FontWeight.w300,
                                  fontSize: 12.sp,
                                  color: selectdIPId == _settingIp.id
                                      ? const Color(0xFFEA4B9B)
                                      : const Color(0xFF262626)),
                            )
                          ],
                        ))),
              ),
            ],
    );
  }

  Widget renderItem(EcyGoodsHomeIPModel item) {
    if (item.id == "-1") {
      return SizedBox(
        width: 44.w,
        height: 44.w,
        child: selectdIPId.isNotEmpty
            ? Image.asset("assets/images/ic_home_ip_all_blue.png")
            : Image.asset("assets/images/ic_home_ip_all_red.png"),
      );
    } else if (item.id == "-2") {
      return SizedBox(
        width: 44.w,
        height: 44.w,
        child: Image.asset(item.iconUrl ?? ""),
      );
    } else {
      return CachedNetworkImage(
        width: 44.w,
        height: 44.w,
        imageUrl: item.iconUrl ?? "",
        imageBuilder: (context, imageProvider) => Container(
          decoration: BoxDecoration(
              border: Border.all(
                  color: selectdIPId == item.id
                      ? const Color(0xFFEA4B9B)
                      : const Color(0x00ffffff),
                  width: selectdIPId == item.id ? 1 : 0),
              borderRadius: BorderRadius.all(Radius.circular(8.r)),
              image: DecorationImage(image: imageProvider, fit: BoxFit.cover)),
        ),
        // placeholder: (context, url) =>
        //     CircularProgressIndicator(),
        errorWidget: (context, url, error) =>
            Image.asset("assets/images/app_icon.png"),
      );
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }
}
